package com.naiterui.ehp.bs.weixin.service.impl;

import cn.hutool.core.util.StrUtil;
import com.naiterui.common.redis.RedisUtil;
import com.naiterui.ehp.bs.weixin.properties.WeixinProperties;
import com.naiterui.ehp.bs.weixin.service.IAccessTokenService;
import com.naiterui.ehp.bs.weixin.wechat.WeChatApiUtil;
import com.naiterui.ehp.bs.weixin.wechat.WeChatCache;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

/**
 * @author zhoupeipei
 * @date 2019-06-14 15:28
 * @since 1.0.0
 */
@Service
@RequiredArgsConstructor
public class AccessTokenServiceImpl implements IAccessTokenService {
    private final WeixinProperties weixinproperties;

    @Override
    public String accessToken() {
        String expireStr = RedisUtil.hashOps().hget(WeChatCache.ACCESS_TOEKN, "expire");
        long expire = StrUtil.isBlank(expireStr) ? 0L : Long.parseLong(expireStr);
        if(System.currentTimeMillis() > expire){
            return WeChatApiUtil.getAccessToken(weixinproperties.getAppId(), weixinproperties.getSecret());
        }
        return RedisUtil.hashOps().hget(WeChatCache.ACCESS_TOEKN, "value");
    }
}
